package com.flower.controller;

import com.flower.pojo.Flower;
import com.flower.service.FlowerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

@Controller
@RequestMapping("/flowers")
public class FlowerController {

    private final FlowerService flowerService;

    @Autowired
    public FlowerController(FlowerService flowerService) {
        this.flowerService = flowerService;
    }

    @GetMapping
    public String listFlowers(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String category,
            @RequestParam(required = false) String priceRange,
            @RequestParam(required = false) String stock,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Model model) {
        
        // 获取符合条件的花卉列表
        List<Flower> flowerList = flowerService.searchFlowers(keyword, category, priceRange, stock);
        
        // 确保页码有效
        int totalItems = flowerList.size();
        int totalPages = (totalItems + size - 1) / size; // 向上取整计算总页数
        
        if (totalPages > 0 && page >= totalPages) {
            page = totalPages - 1; // 如果当前页超出范围，设置为最后一页
        }
        
        // 手动实现分页
        int start = Math.min(page * size, totalItems);
        int end = Math.min((page + 1) * size, totalItems);
        
        List<Flower> pageContent = flowerList.isEmpty() ? flowerList : flowerList.subList(start, end);
        Page<Flower> flowerPage = new PageImpl<>(pageContent, PageRequest.of(page, size), totalItems);
        
        // 将分页数据添加到模型中
        model.addAttribute("flowers", flowerPage.getContent());
        model.addAttribute("page", page);
        model.addAttribute("size", size);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("totalItems", totalItems);
        
        return "flower-list";
    }

    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("flower", new Flower());
        return "flower-form";
    }

    @PostMapping("/save")
    public String saveFlower(@ModelAttribute Flower flower, RedirectAttributes redirectAttributes) {
        flowerService.saveFlower(flower);
        redirectAttributes.addFlashAttribute("message", "花卉信息保存成功！");
        return "redirect:/flowers";
    }

    @GetMapping("/edit/{id}")
    public String showEditForm(@PathVariable Long id, Model model, RedirectAttributes redirectAttributes) {
        return flowerService.getFlowerById(id)
                .map(flower -> {
                    model.addAttribute("flower", flower);
                    return "flower-form";
                })
                .orElseGet(() -> {
                    redirectAttributes.addFlashAttribute("error", "未找到ID为 " + id + " 的花卉信息！");
                    return "redirect:/flowers";
                });
    }

    @GetMapping("/delete/{id}")
    public String deleteFlower(@PathVariable Long id, RedirectAttributes redirectAttributes) {
        flowerService.deleteFlower(id);
        redirectAttributes.addFlashAttribute("message", "花卉信息删除成功！");
        return "redirect:/flowers";
    }
} 